//
//  ViewController.m
//  study
//
//  Created by codew on 5/31/21.
//

#import "ViewController.h"

#import "XYThread.h"

/**
 ====================================================================================
 
                                使用Timer方式做常驻线程
 
 ====================================================================================
 */

@interface ViewController ()

@property (nonatomic, strong) XYThread * thread;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) NSTimer *timer;


@property (nonatomic, strong) XYThread * thread2;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.thread = [[XYThread alloc] initWithTarget:self selector:@selector(execute) object:nil];
    [self.thread start];
    
    // 测试其他线程会不会死!!!!!!!!!
    [self test2];
}

- (void)execute
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(getNetworkStatus) userInfo:nil repeats:YES];
    
    _timer = timer;
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    
    NSLog(@"runloop 挂了......打印了没?");
}




- (void)getNetworkStatus
{
//    [self performSelector:@selector(methodRun) onThread:self.thread withObject:nil waitUntilDone:YES];
    NSLog(@"获取网络状态, 没网了的话提醒一下~, 再看看当前线程: %@", [NSThread currentThread]);
}



- (void)otherMethod
{
    self.count++;
    NSLog(@"%s, , 再看看当前线程: %@", __func__, [NSThread currentThread]);
    
    if (self.count == 5) {
        
        
        // 移除timer可以停掉runloop
//        CFRunLoopRef runLoopRef = CFRunLoopGetCurrent();
//        CFRunLoopRemoveTimer(runLoopRef, (CFRunLoopTimerRef)self.timer, kCFRunLoopDefaultMode);
        
        // 干掉线程也能 停掉runloop
        NSLog(@"count: %zd  杀死thread, 停止runloop", self.count);
        [self.thread cancel];
        [NSThread exit];
        self.thread = nil;
        
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self performSelector:@selector(otherMethod) onThread:self.thread withObject:nil waitUntilDone:NO];
}











/**
 ====================================================================================
 
                                测试这个线程会不会死!!!!!!!!!
 
 ====================================================================================
 */

- (void)test2
{
    self.thread2 = [[XYThread alloc] initWithTarget:self selector:@selector(execute2) object:nil];
    [self.thread2 start];
}

- (void)execute2
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(getNetworkStatus2) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    
    
}

- (void)getNetworkStatus2
{
    NSLog(@"22222********获取网络状态, 没网了的话提醒一下~, 再看看当前线程: %@", [NSThread currentThread]);
}
@end
